package org.sword.wechat4j.user;


import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.sword.lang.HttpUtils;
import org.sword.wechat4j.exception.WeChatException;
import org.sword.wechat4j.token.TokenProxy;
import org.sword.wechat4j.util.WeChatUtil;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
/**
 * 用户管理
 * @author 吴人龙
 */
public class UserManager {

	Logger logger = Logger.getLogger(UserManager.class);
	private String accessToken;
	//获取用户列表
	private static final String USRE_GET_URL = "https://api.weixin.qq.com/cgi-bin/user/get?access_token=";
	//设置用户备注名
	private static final String USER_UPDATE_REMARK_POST_URL="https://api.weixin.qq.com/cgi-bin/user/info/updateremark?access_token=";
	//获取用户基本信息
	private static final String USER_INFO_GET_URL="https://api.weixin.qq.com/cgi-bin/user/info?access_token=";
	//批量获取用户基本信息
	private static final String USRE_MANY_INFO_GET_URL = "https://api.weixin.qq.com/cgi-bin/user/info/batchget?access_token=";
	//创建标签
	private static final String TAG_CREATE_POST_URL="https://api.weixin.qq.com/cgi-bin/tags/create?access_token=";
	//删除标签
	private static final String TAG_DELETE_POST_URL="https://api.weixin.qq.com/cgi-bin/tags/delete?access_token=";
	//查询所有标签
	private static final String TAG_GET_POST_URL="https://api.weixin.qq.com/cgi-bin/tags/get?access_token=";
	//查询用户所在标签列表
	private static final String TAG_GETIDLIST_POST_URL="https://api.weixin.qq.com/cgi-bin/tags/getidlist?access_token=";
	//修改标签名
	private static final String TAG_UPDATE_POST_URL="https://api.weixin.qq.com/cgi-bin/tags/update?access_token=";
	//批量为用户打标签
	private static final String TAG_MANY_ADD_POST_URL="https://api.weixin.qq.com/cgi-bin/tags/members/batchtagging?access_token=";
	//批量为用户取消标签
	private static final String TAG_MANY_DEL_POST_URL="https://api.weixin.qq.com/cgi-bin/tags/members/batchuntagging?access_token=";
	
	public UserManager() {
		this.accessToken = TokenProxy.accessToken();
	}
	/**
	 * 获取所有的关注者列表
	 * @return
	 */
	public List<String> allSubscriber(){
		Follwers follwers = subscriberList();
		String nextOpenId = follwers.getNextOpenid();
		while (StringUtils.isNotBlank(nextOpenId)) {
			Follwers f = subscriberList(nextOpenId);
			nextOpenId = f.getNextOpenid();
			if (f.getData()!=null) {
				follwers.getData().getOpenid().addAll(f.getData().getOpenid());				
			}
		}
		return follwers.getData().getOpenid();
	}
	/**
	 * 获取帐号的关注者列表前10000人
	 * @return
	 */
	public Follwers subscriberList(){
		return subscriberList(null);
	}
	/**
	 * 获取帐号的关注者列表
	 * @param nextOpenId
	 * @return
	 */
	public Follwers subscriberList(String nextOpenId){
		String url = USRE_GET_URL + accessToken;
		if(StringUtils.isNotBlank(nextOpenId)){
			url += "&next_openid=" + nextOpenId;
		}
		String resultStr = HttpUtils.get(url);
		logger.info("return data "+resultStr);
		try {
			WeChatUtil.isSuccess(resultStr);
		} catch (WeChatException e) {
			logger.error(e.getMessage());
			e.printStackTrace();
			return null;
		}
		return JSONObject.parseObject(resultStr, Follwers.class);
	}
	/**
	 * 设置用户备注名
	 * @param openid 用户openid
	 * @param remark 新的备注名，长度必须小于30字符
	 * @return
	 * @throws WeChatException 
	 */
	public void updateRemark(String openId,String remark) throws WeChatException{
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("openid", openId);
		jsonObject.put("remark", remark);
		String requestData = jsonObject.toString();
		logger.info("request data "+requestData);
		String resultStr = HttpUtils.post(USER_UPDATE_REMARK_POST_URL+this.accessToken,requestData);
		logger.info("return data "+resultStr);
		WeChatUtil.isSuccess(resultStr);
	}
	/**
	 * 获取用户基本信息
	 * @param openid 普通用户的标识，对当前公众号唯一
	 * @return
	 */
	public User getUserInfo(String openId){
		return getUserInfo(openId, null);
	}
	/**
	 * 获取用户基本信息
	 * @param openid 普通用户的标识，对当前公众号唯一
	 * @param lang 返回国家地区语言版本，zh_CN 简体，zh_TW 繁体，en 英语
	 * @return
	 */
	public User getUserInfo(String openId,LanguageType lang){
		String url = USER_INFO_GET_URL+this.accessToken+"&openid="+openId;
		if (lang!=null) {
			url+="&lang="+lang.name();
		}
		String resultStr = HttpUtils.get(url);
		try {
			WeChatUtil.isSuccess(resultStr);
		} catch (WeChatException e) {
			logger.error(e.getMessage());
			e.printStackTrace();
			return null;
		}
		User user = JSONObject.parseObject(resultStr, User.class);
		return user;
	}
	/**
	 * 批量获取用户基本信息
	 * @param openIds
	 * @param lang
	 * @return
	 */
	public List<User> getManyUserInfo(List<String> openIds,LanguageType lang){
		List<List<JSONObject>> params = new ArrayList<List<JSONObject>>();
		List<JSONObject> arr = new ArrayList<JSONObject>();
		for(int i=1; i<=openIds.size(); i++){
			JSONObject trem = new JSONObject();
			trem.put("openid", openIds.get(i-1));
			trem.put("lang", lang);
			arr.add(trem);
			if(i==openIds.size() || i%100==0){
				params.add(arr);
				arr = new ArrayList<JSONObject>();
			}
		}
		String url = USRE_MANY_INFO_GET_URL +this.accessToken;
		List<User> resultData = new ArrayList<User>();
		for(List<JSONObject> data : params){
			JSONObject requestData = new JSONObject();
			requestData.put("user_list", data);
			String resultStr = HttpUtils.post(url,requestData.toString());
			try {
				WeChatUtil.isSuccess(resultStr);
			} catch (WeChatException e) {
				logger.error(e.getMessage());
				e.printStackTrace();
				return null;
			}
			UserList userlist = JSONObject.parseObject(resultStr,UserList.class);
			if(userlist!=null && userlist.getUserList().size()>0){
				resultData.addAll(userlist.getUserList());
			}
		}
		return resultData;
	}
	/**
	 * 创建标签
	 * @param name  标签名字（30个字符以内）
	 * @return 
	 * @throws WeChatException 
	 */
	public Tag createTag(String name) throws WeChatException{
		JSONObject nameJson =new JSONObject();
		JSONObject tagJson =new JSONObject();
		nameJson.put("name", name);
		tagJson.put("tag", nameJson);
		String requestData=tagJson.toString();
		logger.info("request data "+requestData);
		String resultStr = HttpUtils.post(TAG_CREATE_POST_URL+this.accessToken, requestData);
		logger.info("return data "+resultStr);
		WeChatUtil.isSuccess(resultStr);
		return JSONObject.parseObject(resultStr).getObject("tag", Tag.class);
	}
	/**
	 * 查询所有标签
	 * @return
	 */
	public List<Tag> getTags(){
		String resultStr = HttpUtils.post(TAG_GET_POST_URL+this.accessToken);
		logger.info("return data "+resultStr);
		try {
			WeChatUtil.isSuccess(resultStr);
		} catch (WeChatException e) {
			logger.error(e.getMessage());
			e.printStackTrace();
			return null;
		}
		JSONObject jsonObject = JSONObject.parseObject(resultStr);
		List<Tag> tags = JSON.parseArray(jsonObject.getString("tags"), Tag.class);
		return tags;
	}
	/**
	 *  查询用户所在标签列表
	 * @param openId 用户的OpenID
	 * @return 用户所属的tagid
	 */
	public List<Tag> getIdTagList(String openId){
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("openid", openId);
		String requestData = jsonObject.toString();
		logger.info("request data "+requestData);
		String resultStr = HttpUtils.post(TAG_GETIDLIST_POST_URL+this.accessToken, requestData);
		logger.info("return data "+resultStr);
		try {
			WeChatUtil.isSuccess(resultStr);
		} catch (WeChatException e) {
			logger.error(e.getMessage());
			e.printStackTrace();
			return null;
		}
		List<Tag> tags = JSON.parseArray(jsonObject.getString("tagid_list"), Tag.class);
		return tags;
	}
	/**
	 * 修改标签名
	 * @param tagId 标签id
	 * @param name 标签名称
	 * @throws WeChatException 
	 */
	public void updateTag(int tagId,String name) throws WeChatException{
		JSONObject nameJson =new JSONObject();
		JSONObject tagJson =new JSONObject();
		nameJson.put("id", tagId);
		nameJson.put("name", name);
		tagJson.put("tag", nameJson);
		String requestData = tagJson.toString();
		logger.info("request data "+requestData);
		String resultStr = HttpUtils.post(TAG_UPDATE_POST_URL+this.accessToken,requestData);
		logger.info("return data "+resultStr);
		WeChatUtil.isSuccess(resultStr);
	}
	/**
	 * 批量为用户打标签
	 * 标签功能目前支持公众号为用户打上最多三个标签。
	 * @param openid 用户的OpenID（size不能超过50）
	 * @param tagid 标签id
	 * @throws WeChatException 
	 */
	public void manyAddTag(String[] openIds,int tagid) throws WeChatException{
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("openid_list", openIds);
		jsonObject.put("tagid", tagid);
		String requestData = jsonObject.toString();
		logger.info("request data "+requestData);
		String resultStr = HttpUtils.post(TAG_MANY_ADD_POST_URL+this.accessToken,requestData);
		logger.info("return data "+resultStr);
		WeChatUtil.isSuccess(resultStr);
	}
	/**
	 * 批量为用户取消标签
	 * @param openids 用户唯一标识符openid的列表（size不能超过50）
	 * @param tagid 标签id
	 * @return 是否修改成功
	 * @throws WeChatException 
	 */
	public void manyDelTag(String [] openIds,int tagid) throws WeChatException{
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("openid_list", openIds);
		jsonObject.put("tagid", tagid);
		String requestData = jsonObject.toString();
		logger.info("request data "+requestData);
		String resultStr = HttpUtils.post(TAG_MANY_DEL_POST_URL+this.accessToken,requestData);
		logger.info("return data "+resultStr);
		WeChatUtil.isSuccess(resultStr);
	}
	/**
	 * 删除标签
	 * @param tagId
	 * @throws WeChatException 
	 */
	public void deleteTag(int tagId) throws WeChatException{
		JSONObject idJson = new JSONObject();
		idJson.put("id", tagId);
		JSONObject tagJson = new JSONObject();
		tagJson.put("tag", idJson);
		String requestData = tagJson.toJSONString();
		logger.info("request data "+requestData);
		String resultStr = HttpUtils.post(TAG_DELETE_POST_URL+this.accessToken,requestData);
		logger.info("return data "+resultStr);
		WeChatUtil.isSuccess(resultStr);
	}
}
